﻿// 监听来自content-script的消息
var domain = "https://mis.517.cn";
var urlApi = "https://misapi2020.517api.cn/mangoapi/b1099_Common.Data/VMlinkRelation/Init";

// 后台监听事件消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    chrome.action.setIcon({
        path: { "128": "/images/icon.png" },
        tabId: sender.tab.id
    });
    setNum(sender.tab.id, message.url, message.title);
    return true;
});

function setNum(tabId, url, title) {
    chrome.cookies.getAll({ url: domain, name: 'newframeuidv4' }, function (cookie) {
        var userid = 0;
        if (cookie.length > 0) {
            userid = cookie[0].value;
            postMlink(url, tabId, userid, title);
        }
        chrome.storage.local.set({ userid: userid }, function () { });
    });
}

function postMlink(url, tabId, userid, title) {
    fetch(urlApi, {
        method: 'post',
        body: JSON.stringify({ Url: url, UserId: userid, Title: title, From: 'ChromePlugin' }),
        headers: {
            'Content-Type': 'application/json;charset=utf-8;'
        },
    }).then(response => {
        let result = response.json()
        result.then(ret => {
            if (ret.DataBody[0].RelationTargetCount > -1) {
                var num = ret.DataBody[0].RelationTargetCount + '';
                if (num > 0) {
                    chrome.action.setBadgeText({ text: num + "", tabId: tabId });
                    chrome.action.setBadgeBackgroundColor({ color: "#646464" });
                }
                else {
                    chrome.action.setIcon({
                        path: { "128": "/images/icon_hui.png" },
                        tabId: tabId
                    });
                }

                //缓存
                var cacheName = "mlink_" + tabId;
                chrome.storage.local.set({ [cacheName]: ret.DataBody[0].MLinkObjId.toString() }, function () { });
            }
        })
    });
}


//关闭tab监听
chrome.tabs.onRemoved.addListener(function (tabId, removeInfo) {
    //console.log("chrome tab remove begin, tabId: " + tabId);
});

// 窗口移除事件监听
chrome.windows.onRemoved.addListener(function (windowId) {
    //console.log("Mlink Chrome插件已卸载: " + windowId);
});

//插件安装监听事件
chrome.runtime.onInstalled.addListener(() => {
    chrome.storage.local.clear();// 清除插件所有的本地数据    
    chrome.storage.sync.clear();//local(本地) sync(同步)
    //console.log("Mlink Chrome插件已安装.");
});


/* 调试 popup */
//chrome.runtime.onInstalled.addListener(async () => {
//    let url = chrome.runtime.getURL("popup/index.html");
//    let tab = await chrome.tabs.create({ url });
//});

/*---------自定义方法------------------------------------------------------ */

/**获取本地文件
 *   (async () => {
        const data = await getUserData();
        console.log(data);
    })();
 * */
async function getUserData() {
    try {
        let response = await fetch("../manifest.json", {
            method: 'GET',
            async: false,
            headers: {
                'Content-Type': 'application/json'
            },
            'contentType': 'json'
        });

        return await response.json();
    } catch (error) {
        console.log('Request Failed', error);
    }
}


// 如果manifest.json未配置 action.default_popup，点击扩展按钮会触发此事件
// https://developer.chrome.com/docs/extensions/reference/action/
chrome.action.onClicked.addListener(function (tab) {
    debugger
    // 设置标题
    chrome.action.setTitle({ tabId: tab.id, title: "You are on tab:" + tab.id });
    // 设置文字
    chrome.action.setBadgeText({ text: "ON" });
});



chrome.contextMenus.create({
    id: '01',
    title: 'Frame',
    contexts: ['all']
});

chrome.contextMenus.create({
    id: '0101',
    title: '复制当前url',
    contexts: ['all'],
    parentId: "01"
});
chrome.contextMenus.create({
    id: '0102',
    title: '复制当前url到[wiki]',
    contexts: ['all'],
    parentId: "01",
});
chrome.contextMenus.create({
    id: '0103',
    title: '复制当前url到[思维导图]',
    contexts: ['all'],
    parentId: "01"
});
chrome.contextMenus.create({
    id: '0104',
    title: '复制当前url到[流程图]',
    contexts: ['all'],
    parentId: "01"
});

chrome.contextMenus.create({
    id: 'wiki-search',
    title: '使用wiki搜索:%s',
    contexts: ['selection'],
    parentId: "01"
});

chrome.contextMenus.onClicked.addListener(function (info, tab) {
    console.log(info);
    console.log(tab.id);
    switch (info.menuItemId) {
        case 'wiki-search':
            chrome.tabs.create({ url: 'https://wiki.517cdn.com/index.php?search=' + encodeURI(info.selectionText) + "*" });
            break;
        case '0103':
            chrome.runtime.sendMessage({ url: "111", title: "222" }, (response) => { });
            break;
        case '0104':
            chrome.tabs.sendMessage(tab.id, { from: 'background发出的消息1', to: 'content_scripts发出的消息2' }, function (response) {
                console.log(response);
            });
            break;
    }
});

 